﻿@using PMS.Web.FrontUI
@using PMS.Web.Models.Customers

@model CustomerModel
@{
    Layout = "_AdminHomeLayout";
    int ModuleId = (int)ViewBag.ModuleId;
    CustomerSearchModel searchModel = ViewBag.SearchModel as CustomerSearchModel ?? null;

    var availableStoresJsonStr = Html.Convert2JavascriptJsonString(searchModel.AvailableStores, true);

}
@section CssStyles{
    <style type="text/css">
        tbody .layui-table-cell {
            height: 100px !important;
            line-height: 100px;
            white-space: normal;
            /*设置为伸缩容器*/
            display: -webkit-box;
            display: -moz-box;
            display: -ms-flexbox;
            display: -webkit-flex;
            display: flex;
            /*垂直居中*/
            -webkit-box-align: center; /*旧版本*/
            -moz-box-align: center; /*旧版本*/
            -ms-flex-align: center; /*混合版本*/
            -webkit-align-items: center; /*新版本*/
            align-items: center; /*新版本*/
        }

        .layui-table-fixed tbody .layui-form-checkbox[lay-skin=primary] i {
            margin-left: 15px;
        }
    </style>
}

<div class="layui-card">
    <div class="layui-card-body">
        <div class="layui-collapse">
            <div class="layui-colla-item">
                <h2 class="layui-colla-title">条件查询</h2>
                <div class="layui-colla-content">
                    <form class="layui-form" action="">
                        <div class="layui-form-item">
                            <div class="layui-form-item layui-inline">
                                <label class="layui-form-label">@searchModel.DisplayName(m => m.SelectedStoreIds)</label>
                                <div class="layui-input-inline" style="width: 420px;">
                                    <input type="text" class="layui-hide" name="@searchModel.NameOf(m => m.SelectedStoreIds)" value="@string.Join(",", searchModel.SelectedStoreIds.ToArray())" />
                                    <div id="storeidselect" class="xmselect"></div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-form-item layui-inline">
                                <label class="layui-form-label">@searchModel.DisplayName(m => m.SelectedCustomerRoleIds)</label>
                                <div class="layui-input-inline">
                                    <input type="text" class="layui-hide" name="@searchModel.NameOf(m => m.SelectedCustomerRoleIds)" value="@string.Join(",", searchModel.SelectedCustomerRoleIds.ToArray())" />
                                    <select id="roleidselect" asp-items="@searchModel.AvailableCustomerRoles" lay-filter="roleidselect">
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item layui-inline">
                                <label class="layui-form-label">@searchModel.DisplayName(m => m.SearchCreateDayStart)</label>
                                <div class="layui-input-inline">
                                    <input type="text" id="@searchModel.NameOf(m => m.SearchCreateDayStart)" name="@searchModel.NameOf(m => m.SearchCreateDayStart)" placeholder="查询日期起" autocomplete="off" class="layui-input">
                                </div>
                                <div class="layui-form-mid">-</div>
                                <div class="layui-input-inline">
                                    <input type="text" id="@searchModel.NameOf(m => m.SearchCreateDayEnd)" name="@searchModel.NameOf(m => m.SearchCreateDayEnd)" placeholder="查询日期止" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-form-item layui-inline">
                                <label class="layui-form-label">@searchModel.DisplayName(m => m.SearchEmail)</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="@searchModel.NameOf(m => m.SearchEmail)" placeholder="请输入待查询用户的注册邮箱" autocomplete="off" class="layui-input" />
                                </div>
                            </div>
                            <div class="layui-form-item layui-inline">
                                <label class="layui-form-label">@searchModel.DisplayName(m => m.SearchLoginname)</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="@searchModel.NameOf(m => m.SearchLoginname)" placeholder="请输入待查询用户的登录账号" autocomplete="off" class="layui-input" />
                                </div>
                            </div>
                            <div class="layui-form-item layui-inline">
                                <label class="layui-form-label">@searchModel.DisplayName(m => m.SearchMobile)</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="@searchModel.NameOf(m => m.SearchMobile)" placeholder="请输入待查询用户的手机号码" autocomplete="off" class="layui-input" lay-verify="maxlen11" />
                                </div>
                            </div>
                            <div class="layui-form-item layui-inline">
                                <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="user-query">
                                    <i class="layui-icon layui-icon-search"></i>
                                    查询
                                </button>
                                <button type="reset" class="pear-btn pear-btn-md">
                                    <i class="layui-icon layui-icon-refresh"></i>
                                    重置
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="pms-table" lay-filter="pms-table"></table>
    </div>
</div>
@await Component.InvokeAsync("ModuleButtonTemplet", new { moduleId = ModuleId, position = ModuleButtonGroup.HeadButtonsGroup })
@await Component.InvokeAsync("ModuleButtonTemplet", new { moduleId = ModuleId, position = ModuleButtonGroup.RecordButtonsGroup })

<input type="text" id="gridPageSize" value="@searchModel.AvailablePageSizes" class="layui-hide" />

<script type="text/html" id="accountStatusTpl">
    <div style="width: 100%;">
        <div class="layui-row" style="width:100%; line-height: 30px;">
            <div class="layui-col-md5">@Model.DisplayName(m => m.IsActive)</div>
            <div class="layui-col-md7">
                {{#  if(d.IsActive){ }}
                <span class="layui-badge layui-bg-green">正常</span>
                {{#  } else { }}
                <span class="layui-badge">锁定</span>
                {{#  } }}
            </div>
        </div>
        <div class="layui-row" style="width:100%; line-height: 30px;">
            <div class="layui-col-md5">注册状态</div>
            <div class="layui-col-md7">
                {{#  if(d.AllowSendingOfWelcomeMessage){ }}
                <span class="layui-badge layui-bg-green">正常</span>
                {{#  } else { }}
                <span class="layui-badge">未激活</span>
                {{#  } }}
            </div>
        </div>
    </div>    
</script>
<script type="text/html" id="datetimeTpl">
    <div style="width: 100%;">
        <div class="layui-row" style="width:100%; line-height: 30px;">
            <div class="layui-col-md5">@Model.DisplayName(m => m.CreatedOnTime)</div>
            <div class="layui-col-md7">{{d.CreatedOnTime}}</div>
        </div>
        <div class="layui-row" style="width:100%; line-height: 30px;">
            <div class="layui-col-md5">@Model.DisplayName(m => m.LastActivityTime)</div>
            <div class="layui-col-md7">{{d.LastActivityTime}}</div>
        </div>
    </div>
</script>
<script type="text/html" id="accountInfoRowTpl">
    <div style="width: 100%;">
        <div class="layui-row" style="width:100%; line-height: 30px;">
            <div class="layui-col-md5">@Model.DisplayName(m => m.LoginName)</div>
            <div class="layui-col-md7">{{d.LoginName}}</div>
        </div>
        <div class="layui-row" style="width:100%; line-height: 30px;">
            <div class="layui-col-md5">@Model.DisplayName(m => m.Mobile)</div>
            <div class="layui-col-md7">{{d.Mobile}}</div>
        </div>
        <div class="layui-row" style="width:100%; line-height: 30px;">
            <div class="layui-col-md5">@Model.DisplayName(m => m.Email)</div>
            <div class="layui-col-md7">{{d.Email}}</div>
        </div>
    </div>
</script>
<script type="text/html" id="pmsRecordMoreTpl">
    <button class="pear-btn pear-btn-sm dropdownmore" id="dropdownmore_{{d.Id}}">
        <span>操作</span>
        <i class="layui-icon layui-icon-triangle-d"></i>
    </button>
</script>
<!-- 下拉内容自定义模板 -->
<script id="dropdownItemTpl" type="text/html">
    {{# layui.each(d.dropdownBtns, function(index, item){ }}
    <div class="layu-menu-item {{item.txtClass}}" lay-event="{{item.event}}" data-moduleid="{{item.moduleId}}" data-buttonid="{{item.buttonId}}">
        <a href="javascript:;" class="{{item.txtClass}}">
            {{#  if(item.layIcon !== "none"){ }}
            <i class="{{ item.layIcon }}"></i>&nbsp;
            {{#  } }}
            <span>{{item.txt}}</span>
        </a>
    </div>
    {{#  }); }}
</script>
@section Scripts{
    <script type="text/javascript">
        layui.use(['table', 'jquery', 'form', 'element', 'lodash', 'xmSelect', 'laydate', 'Cookies', 'http', 'layuidropdown', 'loading'], function () {
            let table = layui.table;
            let $ = layui.jquery;
            let form = layui.form;
            let element = layui.element;
            let lodash = layui.lodash;
            let xmSelect = layui.xmSelect;
            let laydate = layui.laydate;
            let Cookies = layui.Cookies;
            let http = layui.http;
            let dropdown = layui.layuidropdown;
            let loading = layui.loading;

            var getAuthToken = function () {
                const cookieVal = Cookies.get(".PMS.SignInToken");
                return cookieVal != null ? "Bearer " + cookieVal : "";
            };
            var getSearchModelData = function () {
                var searchModel = { //对应后台CustomerSearchModel
                    SelectedCustomerRoleIds: PMSUtils.parseToIntegerArray($("input[name=SelectedCustomerRoleIds]").val()),
                    SelectedStoreIds: PMSUtils.parseToIntegerArray($("input[name=SelectedStoreIds]").val()),
                    SearchCreateDayStart: $("input[name=SearchCreateDayStart]").val(),
                    SearchCreateDayEnd: $("input[name=SearchCreateDayEnd]").val(),
                    SearchEmail: $("input[name=SearchEmail]").val(),
                    SearchLoginname: $("input[name=SearchLoginname]").val(),
                    SearchMobile: $("input[name=SearchMobile]").val(),
                };
                return searchModel;
            };

            //设置查询日期
            var startTime = laydate.render({
                elem: '#SearchCreateDayStart',
                type: 'date',
                btns: ['clear', 'confirm'],
                max: 'nowTime',//默认最大值为当前日期
                done: function (value, date) {
                    //console.log(value); //得到日期生成的值，如：2017-08-18
                    //console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                    endTime.config.min = {
                        year: date.year,
                        month: date.month - 1,//关键
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    };

                }
            })
            var endTime = laydate.render({
                elem: '#SearchCreateDayEnd',
                type: 'date',
                btns: ['clear', 'confirm'],
                max: 'nowTime',
                done: function (value, date) {
                    startTime.config.max = {
                        year: date.year,
                        month: date.month - 1,//关键
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    }

                }
            })
            //归属店铺多选下拉框
            var storeData = @Html.Raw(availableStoresJsonStr) ;
            var storeSelector = xmSelect.render({
                el: '#storeidselect',
                tips: '选择会员注册所属店铺',
                autoRow: true,
                height: 'auto',
                layVerify: 'required',
                layVerType: 'tips',
                data: PMSUtils.isString(storeData) ? $.parseJSON(storeData) : storeData,
                toolbar: { show: true },
                template({ item, sels, name, value }) {
                    return item.name + '<span style="position: absolute; right: 10px; color: #8799a3">' + item.url + '</span>'
                },
                on: function (data) {
                    var selectedStoreIds = lodash.map(data.arr, function (item) {
                        return PMSUtils.toNumber(item.value);
                    });
                    $("input[name=SelectedStoreIds]").val(lodash.join(selectedStoreIds));
                }
            });

            //用户角色查询
            form.on('select(roleidselect)', function (data) {
                $("input[name=SelectedCustomerRoleIds]").val(data.value);
            });
            form.verify({
                maxlen11: function (value, item) { //value：表单的值、item：表单的DOM对象
                    if (value.length > 11) {
                        $(item).focus();
                        return "长度不能超过11位";
                    }
                }
            });
            //列表条件过滤筛选
            form.on('submit(user-query)', function (data) {
                tableConfig.where = getSearchModelData();
                tableIns.reload(tableConfig, true);
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
            let availabePageSize = PMSUtils.parseToIntegerArray($("#gridPageSize").val());
            var tableConfig = {
                id: 'pms-table',
                elem: '#pms-table',
                method: 'post',
                contentType: 'application/json;charset=UTF-8',
                url: backendwebapiConfig.loadcustomerpagedlist,
                request: {
                    pageName: '@searchModel.NameOf(p => p.Page)', //页码的参数名称，默认：page
                    limitName: '@searchModel.NameOf(p => p.PageSize)' //每页数据量的参数名，默认：limit
                },
                where: null,
                headers: null,
                limits: availabePageSize,
                limit:  @searchModel.PageSize,
                skin: 'line',
                toolbar: '#pmsHeadbarTpl',
                defaultToolbar: [{
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh',
                    title: '刷新'
                }, 'filter', 'print', 'exports'],
                page: {
                    curr: 1
                },
                cols: [
                    [
                        { type: "checkbox", width: 50, fixed: 'left', align: 'center' },
                        { field: 'Id', hide: true, title: 'ID' },
                        {
                            field: '@Model.NameOf(p => p.AvatarImage)', title: '@Model.DisplayName(m => m.AvatarImage)', minWidth: 120
                            , event: 'OnImgPreview', align: "center", templet: function (d) {
                                return '<a href="javascript:;" data-index="' + (d.LAY_INDEX - 1) + '"><img src=' + d.AvatarImage.ThumbImageUrl + "?t=" + new Date().getTime() + '></a>';
                            }
                        },
                        { field: '@Model.NameOf(p => p.LoginName)', title: '账号信息', width: 210, templet: "#accountInfoRowTpl" },
                        { field: '@Model.NameOf(p => p.NickName)', title: '@Model.DisplayName(m => m.NickName)', minWidth: 90 },
                        { field: '@Model.NameOf(p => p.Gender)', title: '@Model.DisplayName(m => m.Gender)', minWidth: 60},
                        { field: '@Model.NameOf(p => p.RegisteredInStore)', title: '@Model.DisplayName(m => m.RegisteredInStore)', minWidth: 90},
                        { field: '@Model.NameOf(p => p.CustomerRoleNames)', title: '@Model.DisplayName(m => m.CustomerRoleNames)', minWidth: 185},
                        { field: '@Model.NameOf(p => p.IsActive)', title: '账号状态', width: 180, templet: '#accountStatusTpl'},
                        { field: '@Model.NameOf(p => p.CreatedOnTime)', title: '时间', minWidth: 260, templet: "#datetimeTpl" },
                        { field: '@Model.NameOf(p => p.LastLoginIpAddress)', title: '@Model.DisplayName(m => m.LastLoginIpAddress)', minWidth: 100 },
                        { title: '操作', templet: '#pmsRecordMoreTpl', width: 100, fixed: "right", align: 'center' }
                    ]
                ],
                error: function (e, msg) {
                    if (e.status === 401) { //UnAuthorized
                        var Error401 = http.ajax.defaultError401;
                        if (error.responseJSON) {
                            if (error.responseJSON.error !== undefined) {
                                Error401 = {
                                    message: error.responseJSON.error,
                                    details: error.responseJSON.error_description
                                };
                            }
                        }
                        http.ajax.showError(Error401);
                    }
                },
                parseData: function (res) {
                    return {
                        "code": res.state == 200 ? 0 : -1,     //解析接口状态
                        "msg": res.state == 200 ? "" : res.message,     //解析提示文本
                        "count": res.state == 200 ? res.data.RecordsTotal : 0, //解析数据长度
                        "data": res.state == 200 ? res.data.Data : null,   //解析数据列表
                    };
                },
                done: function (res) {
                    let btnItems = [];
                    var templete = $('#pmsRecordBarTpl')[0].innerHTML;
                    //David: contents inside <script id="demo" type="text/html">...</scirpt>
                    //is text string, not DOM
                    $("<div>" + templete + "</div>").find("button").each(function () {
                        let icon = $(this).find("i");
                        btnItems.push({
                            layIcon: icon.length > 0 ? icon.attr('class') : "none",
                            txt: PMSUtils.trim($(this).text()),
                            txtClass: $(this).hasClass("layui-btn-disabled") ? "layui-btn-disabled" : "",
                            event: $(this).attr("lay-event"),
                            buttonId: $(this).data("buttonid"),
                            moduleId: $(this).data("moduleid"),
                        });
                    });
                    dropdown.suite(".dropdownmore", {
                        align: 'center',
                        data: { dropdownBtns: btnItems },
                        template: "dropdownItemTpl"
                    });
                } //done: function (res) {
            };

            tableConfig.where = getSearchModelData();
            var authToken = getAuthToken();
            if (authToken.length > 0) {
                tableConfig.headers = { 'Authorization': authToken };
            }
            var tableIns = table.render(tableConfig);
            //监听顶部按钮栏
            let editWindowConfig = {
                title: "编辑/修改",
                type: 2,
                content: "",
                fixtolayoutbody: true,
                anim: 3,
                end: function () {
                    if (tableIns == null) {
                        window.location.reload(true);
                    } else {
                        tableConfig.where = getSearchModelData();
                        tableIns.reload(tableConfig, true);
                    }
                }
            };

            table.on('toolbar(pms-table)', function (obj) {
                if (obj.event === 'refresh') {
                    window.location.reload(true);
                    return;
                }
                const $btnElem = $(this);
                const isBtnDisabled = $btnElem.hasClass("layui-btn-disabled");
                if (isBtnDisabled) return false;
                const buttonId = $btnElem.data("buttonid");
                const moduleId = $btnElem.data("moduleid");
                if (obj.event === 'OnAdd') {
                    editWindowConfig.content = bakcendviewConfig.customereditview + "?buttonid=" + buttonId + "&moduleid=" + moduleId;
                    PMSUtils.popupWindow(editWindowConfig);
                }
            });
            //监听表格数据行按钮
            table.on('tool(pms-table)', function (obj) {
                const data = obj.data;
                const $btnElem = $(this);
                const isBtnDisabled = $btnElem.hasClass("layui-btn-disabled");
                if (isBtnDisabled) return false;
                const buttonId = $btnElem.data("buttonid");
                const moduleId = $btnElem.data("moduleid");
                if (obj.event === 'OnImgPreview') {
                    var imgList = lodash.map(table.getData("pms-table"),function (d) {
                        return {
                            alt: d.NickName,
                            src: d.AvatarImage.ImageUrl
                        };
                    });
                 
                    layer.photos({
                        photos: {
                            data: imgList,
                            start: $(this).data('index')
                        },
                        shade: .1,
                        closeBtn: true
                    });
                } else if (obj.event === 'OnEdit') {
                    editWindowConfig.content = bakcendviewConfig.customereditview + "?buttonid=" + buttonId + "&moduleid=" + moduleId + "&customerid=" + data.Id;
                    PMSUtils.popupWindow(editWindowConfig);
                } else if (obj.event === 'OnCustomerRoleAssign') {
                    let popupWinConfig = {
                        title: "用户角色分配",
                        type: 2,
                        content: bakcendviewConfig.customerassignroleview + "?buttonid=" + buttonId + "&moduleid=" + moduleId + "&customerid=" + data.Id,
                        width: 560,
                        height: 500,
                        end: function () {
                            if (tableIns == null) {
                                window.location.reload(true);
                            } else {
                                tableConfig.where = getSearchModelData();
                                tableIns.reload(tableConfig, true);
                            }
                        }
                    };
                    PMSUtils.popupWindow(popupWinConfig);
                } else if (obj.event === 'OnDelete') {
                    layer.confirm('删除用户将注销用户相关所有信息,请谨慎操作。是否继续?',
                        { icon: 3, title: '提示' },
                        function (index) {
                            http.post(backendwebapiConfig.customerdelete,
                                {
                                    Id: data.Id,
                                    ModuleId: moduleId,
                                    ButtonId: buttonId,
                                },
                                function () { //beforeSend
                                    loading.Load(1, '');
                                }
                            ).done(function (response) {
                                if (response.state && response.state === 200) {
                                    obj.del();
                                }
                            }).fail(function (error) {
                                http.ajax.logError(error);
                            }).always(function () {
                                loading.loadRemove(500);
                                dropdown.hide(".layui-table-fixed #dropdownmore_" + data.Id);
                            });
                            layer.close(index);
                        },
                        function () {
                            dropdown.hide(".layui-table-fixed #dropdownmore_" + data.Id);
                        }
                    );
                } 
            });
        });
    </script>
}
